<template>
	<view class="kefu_container">
		<!-- 留言 -->
		<view class="main_header">
			<text id="header_title">咨询师 Mark 为您服务</text>
			<text id="csr_status" style="color: rgb(60, 118, 61);">• 在线</text>
			<text id="kefu_error"></text>
			<!-- <i class="fa fa-close fa-lg fa-fw back_page"></i> -->
		</view>
		<!-- 内容 -->
		<view class="content_wrapper">
			<view class="chat_wrapper">
				<scroll-view
					@scrolltoupper="scrollTop"
					id="kefu_scroll"
					:scroll-y="true"
					:scroll-with-animation="kefu_scroll_with_animation"
					:scroll-top="kefu_scroll_top"
					@scroll="scroll"
				>
					<block v-for="(item,index) in record_msg" :key="index">
						<view class="bubble me" v-if="item.sender_id == user_info.id">
							<text>{{item.message}}</text>
							<text class="kefu_message_status kefu_message_51513">未读</text>
						</view>
						<view class="bubble you" v-else>
							<text>{{item.message}}</text>
							<text class="kefu_message_status kefu_message_51513" v-if="item.status==0">未读</text>
						</view>
					</block>
				</scroll-view>
			</view>
			<view class="write">
				<view class="widget_textarea">
					<textarea id="kefu_message" spellcheck="false" style="height: 35px;" v-model="message"></textarea>
				</view>
				<view class="write_right">
					<button class="btn btn-sm send_btn dis-inline-block" @click="chat">发送</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { recordAdd, adSession, historyRecord } from '@/utils/http'
export default {
	data() {
		return {
			order_no: '',
			client_id: '',
			session_id: '',
			user_info: '',
			message: '', //发送消息
			record_msg: [],
			index_page: 0,
			total_page: 1,
			ws: {
				SocketTask: null,
				Timer: null, // 计时器
				ErrorMsg: [], // 发送失败的消息
				MaxRetryCount: 3, // 最大重连次数
				CurrentRetryCount: 0,
				socketOpen: false,
				pageHideCloseWs: true, // 是否在页面hide时关闭链接，兼容预览图片的情况
				unloadCloseWs: false // ws关闭状态码兼容性不好，手动标记页面卸载关闭ws链接
			},
			kefu_scroll_with_animation: true,
			kefu_scroll_top: 0
		}
	},
	methods: {
		//滚动的操作
		scroll(e) {
			console.log(e)
		},
		//加载更多历史聊天记录
		scrollTop() {
			if (this.index_page < this.total_page) {
				this.getHistoryRecord()
			} else {
				this.errorToShow('没有更多')
			}
		},
		scroll_into_footer: function(timeout = 0, kefu_scroll_top = 0) {
			var that = this
			if (kefu_scroll_top) {
				setTimeout(function() {
					that.kefu_scroll_top =
						that.kefu_scroll_top > 99990
							? that.kefu_scroll_top + 200
							: kefu_scroll_top
				}, timeout)
				return
			}
			let kefu_scroll = uni.createSelectorQuery().select('#kefu_scroll')
			kefu_scroll
				.fields({ scrollOffset: true }, data => {
					setTimeout(function() {
						that.kefu_scroll_top = data.scrollHeight
					}, timeout)
				})
				.exec()
		},
		// 滚动操作结束

		//获取聊天记录
		getHistoryRecord() {
			historyRecord({
				session_id: this.session_id,
				client_id: this.client_id,
				page: this.index_page + 1
			}).then(res => {
				if (res) {
					this.index_page = res.current_page
					this.total_page = res.last_page
					let msgs = res.data
					msgs.sort(function(a, b) {
						return a['id'] - b['id']
					})
					if (res.current_page == 1) {
						this.record_msg = [...this.record_msg, ...res.data]
						this.scroll_into_footer()
					} else {
						this.record_msg = [...res.data, ...this.record_msg]
						this.scroll_into_footer(0, 60)
					}
				}
			})
		},

		//创建一条回话日志
		async createRecordSession() {
			await adSession({
				client_id: this.client_id,
				order_no: this.order_no
			}).then(res => {
				this.session_id = res.id
			})
		},

		//连接成功调用初始化设置函数
		async init(msg) {
			this.client_id = msg.client_id
			//创建回话
			await this.createRecordSession()
			this.getHistoryRecord()
		},
		//发送消息
		chat() {
			recordAdd({
				client_id: this.client_id,
				message: this.message,
				session_id: this.session_id
			}).then(res => {
				this.record_msg.push({
					session_id: this.session_id,
					message: this.message,
					status: 0,
					sender_id: this.user_info.id
				})
				this.message = ''
				this.scroll_into_footer()
			})
		},
		//链接socket
		connectSocket() {
			let _that = this

			if (this.ws.SocketTask && this.ws.socketOpen) {
				console.log('无需链接')
				return
			}

			// 开始链接
			_that.ws.SocketTask = uni.connectSocket({
				url: 'ws://test.lqscc.com:1818',
				header: {
					'auth-token': uni.getStorageSync('user_info').token || '',
					'content-type': 'application/json'
				},
				complete: res => {}
			})

			// 链接打开
			uni.onSocketOpen(function(res) {
				console.log('链接已打开')
				_that.ws.socketOpen = true
				_that.ws.CurrentRetryCount = 0
				// 重新发送所有出错的消息
				for (let i in _that.ws.ErrorMsg) {
					_that.wsSend(_that.ws.ErrorMsg[i])
				}
				_that.ws.ErrorMsg = []
				_that.errorTips = ''

				if (_that.ws.Timer != null) {
					clearInterval(_that.ws.Timer)
				}

				_that.ws.Timer = setInterval(_that.ws_send, 28000) //定时发送心跳
			})

			// 收到消息
			uni.onSocketMessage(function(res) {
				let msg = JSON.parse(res.data)
				// console.log(_that[msg.type])
				try {
					if (_that[msg.type]) {
						let actions = _that[msg.type]
						actions.call(this, msg)
					}
				} catch (error) {
					console.log(error)
				}

				// msg.type.call(this.msg)
				// let type = res.type
				// res.type.call(this.msg)

				// let actions = that.domsg()
				// let action = actions[msg.msgtype] || actions['default']
				// action.call(this, msg)
			})

			// 出错
			uni.onSocketError(function(res) {
				_that.ws.socketOpen = false
				_that.errorTips = 'WebSocket 发生错误!'
				console.log('链接出错', res)
			})

			// 链接关闭
			uni.onSocketClose(function(res) {
				// 工具上是1000，真机上测试是10000
				console.log('链接已关闭', res)
				_that.ws.socketOpen = false

				if (_that.ws.Timer != null) {
					clearInterval(_that.ws.Timer)
				}

				if (_that.errorTips.indexOf('重连') === -1) {
					_that.errorTips = '网络链接已断开!'
				}

				if (
					res.code == 1000 ||
					res.code == 10000 ||
					_that.ws.unloadCloseWs
				) {
					return
				}

				if (_that.ws.MaxRetryCount) {
					_that.ws.Timer = setInterval(_that.retry_websocket, 3000) //每3秒重新连接一次
				}
			})
		},
		wsSend(message) {
			let _that = this
			if (!message) {
				message = {
					message: 'Message',
					type: 'ping'
				}
			}
			// const client_id = this.client_id
			message = Object.assign(message, { client_id: this.client_id })

			if (_that.ws.SocketTask && _that.ws.socketOpen) {
				uni.sendSocketMessage({
					data: JSON.stringify(message)
				})
			} else {
				console.log(
					'消息发送出错',
					message,
					_that.ws.SocketTask,
					_that.ws.socketOpen
				)
				_that.ws.ErrorMsg.push(message)
			}
		}
	},

	onLoad() {
		console.log(123)

		this.order_no = this.options.order_no || ''
		//创建一条回话消息
		this.connectSocket()
		//获取用户信息
		const user_info = uni.getStorageSync('user_info')
		if (user_info) {
			this.user_info = user_info
		}
		//this.kefu_scroll_top = 245
		//console.log(window.top)
	},
	onUnload() {
		if (this.ws.SocketTask && this.ws.socketOpen) {
			console.log('页面卸载主动关闭链接')
			this.ws.unloadCloseWs = true
			uni.closeSocket()
		}
	}
}
</script>

<style scoped>
.kefu_container {
	position: relative;
	height: 100vh;
}
.main_header {
	position: relative;
	display: block;
	height: 40px;
	padding: 0 10px;
	background: #f5f5f5;
	line-height: 40px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	border-bottom: 1px solid #e1e3e9;
}
.content_wrapper {
	position: absolute;
	top: 40px;
	left: 0;
	right: 0;
	bottom: 0;
	overflow: hidden;
}
.chat_wrapper {
	height: calc(100vh - 100px);
	padding: 10px 14px 0px 14px;
}
.chat_wrapper scroll-view {
	height: 100%;
}
/* .chat_wrapper {
	position: absolute;
	top: 0px;
	bottom: 52px;
	background-color: #f5f5f5;
	width: 100%;
	border-bottom: 1px solid #e1e3e9;
	box-sizing: border-box;
	color: #181818;
	overflow-x: hidden;
	overflow-y: auto;
	
} */

.chat_wrapper .bubble.you {
	float: left;
	color: #181818;
	background-color: #fff;
	align-self: flex-start;
	word-wrap: break-word;
	word-break: break-all;
}
.chat_wrapper .bubble {
	font-size: 16px;
	position: relative;
	display: inline-block;
	clear: both;
	margin-bottom: 8px;
	padding: 13px 14px;
	vertical-align: top;
	border-radius: 5px;
	max-width: 86%;
}
.chat_wrapper .bubble:before {
	position: absolute;
	top: 19px;
	display: block;
	width: 8px;
	height: 6px;
	content: '\00a0';
	transform: rotate(29deg) skew(-35deg);
}
.chat_wrapper .bubble.me .kefu_message_status {
	position: absolute;
	bottom: 0;
	left: -30px;
	color: #00b0ff;
	font-size: 12px;
}

.chat_wrapper .bubble.me {
	float: right;
	color: #fff;
	background-color: #00b0ff;
	align-self: flex-end;
	word-wrap: break-word;
	word-break: break-all;
}
.chat_wrapper .bubble.you:before {
	left: -3px;
	background-color: #fff;
}
.chat_wrapper .bubble.me:before {
	right: -3px;
	background-color: #00b0ff;
}
.content_wrapper .write {
	position: absolute;
	bottom: 0;
	height: auto;
	box-sizing: border-box;
	background-color: #f7f7f7;
	box-shadow: 0 -1px 0 #e5e5e5;
	width: 100%;
	padding: 4px 6px;
	display: flex;
	align-items: center;
}
.widget_textarea {
	flex: 8;
}
#kefu_message {
	box-sizing: border-box;
	overflow-y: auto;
	max-height: 52px;
	top: 0;
	width: 96%;
	outline: none;
	border: none;
	resize: none;
	margin: 4px 0 1px 6px;
	border-radius: 4px;
	padding: 4px;
	overflow-x: hidden;
	user-select: text !important;
	line-height: 17px;
	font-size: 17px;
	color: #181818;
}
.btn-sm {
	color: #fff;
	outline: none;
	background-color: #00b0ff;
	border-color: #00b0ff;
	padding: 5px 10px;
	font-size: 12px;
	line-height: 1.5;
	border-radius: 3px;
}
</style>